package pnu.ssm.sbmother;

import pnu.ssm.key.Key;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.MotionEvent;
import android.view.Window;

public class SplashActivity extends Activity {
	
	public static final String TAG = "SplashActivity";
	private int _splashTime = 3000;
	private Thread splashTread ;
	boolean isLogin;
	private SharedPreferences pref;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_splash);
		buildUI();
		startSplash();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		isNetworkConnected();
	}
	
	private void buildUI(){
		splashTread = new SplashThread();
		pref = getSharedPreferences(Key.prefKey, MODE_PRIVATE);
		isLogin = pref.getBoolean(Key.isLogin, false); 
	}
	
	private void startSplash(){ splashTread.start(); }
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
	    	synchronized(splashTread){ splashTread.notifyAll(); }
	    }
	    return true;
	}

	private class SplashThread extends Thread {
		@Override
		public void run() {
			try { synchronized (this) { wait(_splashTime); } } 
			catch (InterruptedException e) { Log.e(TAG, e.getMessage()); } 
			finally {
				finish();
				Intent intent = null;
				if(isLogin){ intent = new Intent(SplashActivity.this, SelectActivity.class); }
				else{ intent = new Intent(SplashActivity.this, LoginActivity.class); }
				startActivity(intent);
			}
		}
	}
	
	private boolean isNetworkConnected() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
		if (ni == null) {
			showDialog();
			return false;
		} else
			return true;
	}
	private void showDialog(){
		String msg = "인터넷이 연결되어 있지 않아 서버 접속이 불가합니다. 인터넷을 연결한 후 접속해주세요";
		
	    AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
	    alt_bld.setMessage(msg)
	    .setCancelable(false)
	    .setPositiveButton("확인",new DialogInterface.OnClickListener() {
	        @Override
			public void onClick(DialogInterface dialog, int id) {
	        	finish();
	        }});
	    AlertDialog alert = alt_bld.create();
	    alert.setTitle("Mom's Locker");
	    alert.setIcon(R.drawable.ic_launcher);
	    alert.show();
	}
}
